#include "../StdInc.h"
#include "../database/DataBase.h"
#include "../database/DBCommon.h"
#include <boost/format.hpp>

namespace GSTrader
{
	namespace TradeService
	{
		CMarketDataApi::CMarketDataApi(int nType) : CDataApi(nType)/*, m_nTradeClientId(-1)*/
		{
			m_nApiType = apiMd;
			m_pMarketDataQueue = nullptr;
			m_bSubscribe = false;

			CDataBase* pDataBase = CDataBase::GetInstance();
			if (pDataBase)
			{
				m_pDB = pDataBase->m_pDBCommon;
			}
		}

		CMarketDataApi::~CMarketDataApi()
		{
			m_pMarketDataQueue;
		}

		void CMarketDataApi::AddMarketDataMsg(CMsg* pMsg)
		{
			if (m_pMarketDataQueue == nullptr)
			{
				delete pMsg;
			}
			else
			{
				m_pMarketDataQueue->Push(pMsg);
			}
		}

		bool CMarketDataApi::UpdateDepthMarketData(CDepthMarketData* pMarketData)
		{
			return m_pDB->UpdateMarketData(pMarketData);
		}

		void CMarketDataApi::ReSubscribe()
		{
			if (m_bSubscribe)
			{
				if (m_subscribe.GetCount() > 0)
				{
					Subscribe(&m_subscribe);
				}
			}

			m_bSubscribe = true;
		}

		string CMarketDataApi::GetKey()
		{
			if (m_pConnectionInfo && m_pConnectionInfo->m_pBroker)
			{
				boost::format f("%1%_%2%_%3%");
				f % m_pConnectionInfo->m_pBroker->m_nPlatformType;
				f % m_pConnectionInfo->m_pBroker->m_strBrokerID;
				f % m_nProviderId;
				return f.str();
			}

			return "";
		}

		int	CMarketDataApi::GetSubscribeCount()
		{
			return m_subscribe.GetCount();
		}

		void CMarketDataApi::AddSubscribe(CSubscribeInstrument* pSubscribe)
		{
			m_subscribe.AddSubscribe(pSubscribe);
		}

		void CMarketDataApi::UnAddSubscribe(CSubscribeInstrument* pSubscribe)
		{
			m_subscribe.UnSubscribe(pSubscribe);
		}
	}
}